<template>
  <div class="ai-analyse-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="analysis-card" :body-style="{ padding: '20px' }">
          <template #header>
            <div class="card-header">
              <h2 class="header-title">AI 分析结果</h2>
              <el-button type="primary" :icon="RefreshRight" @click="startNewAnalysis">
                重新分析
              </el-button>
            </div>
          </template>
          
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="6" animated />
            <div class="loading-text">AI 正在分析数据，请稍候...</div>
          </div>
          
          <div v-else>
            <div class="analysis-result">
              <div class="section-title">
                <el-icon><DataAnalysis /></el-icon>
                <span>分析结论</span>
              </div>
              <div class="result-content">
                {{ analysisResult || '暂无分析结果' }}
              </div>
            </div>
            
            <div class="chat-section">
              <div class="section-title">
                <el-icon><ChatDotRound /></el-icon>
                <span>与AI对话</span>
              </div>
              
              <div class="chat-history" ref="chatContainer">
                <div v-for="(message, index) in chatHistory" 
                     :key="index" 
                     class="message-item"
                     :class="{'user-message-container': message.role === 'user',
                             'ai-message-container': message.role === 'assistant'}">
                  <div class="message-avatar">
                    <el-avatar :size="40" :icon="message.role === 'user' ? User : Monitor" />
                  </div>
                  <div class="message-bubble" 
                       :class="{'user-message': message.role === 'user',
                               'ai-message': message.role === 'assistant'}">
                    {{ message.content }}
                  </div>
                </div>
              </div>

              <div class="input-area">
                <el-input
                  v-model="userInput"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入您的问题..."
                  resize="none"
                  @keyup.enter.ctrl="sendMessage"
                />
                <div class="button-group">
                  <el-button type="info" plain @click="clearChat" :icon="Delete">
                    清空对话
                  </el-button>
                  <el-button type="primary" @click="sendMessage" :icon="Position">
                    发送消息
                  </el-button>
                </div>
                <div class="input-tip">提示：按 Ctrl + Enter 快捷发送</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAnalysisStore } from '@/store/analysis'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  RefreshRight,
  ChatDotRound,
  DataAnalysis,
  Delete,
  Position,
  User,
  Monitor
} from '@element-plus/icons-vue'

const router = useRouter()
const analysisStore = useAnalysisStore()
const loading = ref(false)
const analysisResult = ref('')
const userInput = ref('')
const chatHistory = ref([])
const chatContainer = ref(null)

// 滚动到最新消息
const scrollToBottom = async () => {
  await nextTick()
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

// 监听聊天历史变化，自动滚动到底部
watch(chatHistory, () => {
  scrollToBottom()
}, { deep: true })

const analyzeData = (data) => {
  loading.value = true
  try {
    const prompt = `请分析以下数据并给出详细的分析报告：
    1. 视频热度数据：${JSON.stringify(data.videoRank)}
    2. 标签热度数据：${JSON.stringify(data.tabRank)}
    3. 用户喜好数据：${JSON.stringify(data.userFlavor)}
    
    请从以下几个方面进行分析：
    1. 整体趋势分析
    2. 热门内容分析
    3. 用户偏好分析
    4. 潜在机会和建议
    5. 字数不超过300字`

    // 使用代理调用 AI API
    axios.post('/ai-api/v1/chat/completions', {
      messages: [{ role: 'user', content: prompt }],
      model: 'deepseek-chat',
      temperature: 0.7
    }, {
      timeout: 60000 // 超时时间延长至60秒
    })
    .then(response => {
      if (response.data?.choices?.[0]) {
        analysisResult.value = response.data.choices[0].message.content
        chatHistory.value.push({
          role: 'assistant',
          content: analysisResult.value
        })
      }
    })
    .catch(error => {
      console.error('AI分析失败:', error)
      ElMessage.error('AI分析失败，请稍后重试')
    })
    .finally(() => {
      loading.value = false
    })
  } catch (error) {
    console.error('数据处理失败:', error)
    ElMessage.error('数据处理失败')
    loading.value = false
  }
}

const sendMessage = () => {
  if (!userInput.value.trim()) {
    ElMessage.warning('请输入消息内容')
    return
  }

  const userMessage = userInput.value.trim()
  chatHistory.value.push({
    role: 'user',
    content: userMessage
  })
  userInput.value = ''

  // 使用代理调用 AI API
  axios.post('/ai-api/v1/chat/completions', {
    messages: chatHistory.value,
    model: 'deepseek-chat',
    temperature: 0.7
  }, {
    timeout: 60000 // 超时时间延长至60秒
  })
  .then(response => {
    const aiResponse = response.data?.choices?.[0]?.message?.content
    if (aiResponse) {
      chatHistory.value.push({
        role: 'assistant',
        content: aiResponse
      })
    }
  })
  .catch(error => {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败，请稍后重试')
    // 移除用户消息
    chatHistory.value.pop()
  })
}

const clearChat = () => {
  ElMessage.success('对话已清空')
  chatHistory.value = []
  userInput.value = ''
}

const startNewAnalysis = () => {
  // 检查 store 中是否有数据
  if (analysisStore.videoRank.length > 0) {
    ElMessageBox.confirm(
      '是否要重新开始AI分析？',
      '确认分析',
      {
        confirmButtonText: '开始分析',
        cancelButtonText: '暂不分析',
        type: 'info'
      }
    )
    .then(() => {
      analyzeData({
        videoRank: analysisStore.videoRank,
        tabRank: analysisStore.tabRank,
        userFlavor: analysisStore.userFlavor
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消分析'
      })
    })
  } else {
    ElMessage.warning('没有可分析的数据')
  }
}

onMounted(() => {
  // 检查 store 中是否有数据
  if (analysisStore.videoRank.length > 0) {
    ElMessageBox.confirm(
      '是否要开始AI分析？',
      '确认分析',
      {
        confirmButtonText: '开始分析',
        cancelButtonText: '暂不分析',
        type: 'info'
      }
    )
    .then(() => {
      analyzeData({
        videoRank: analysisStore.videoRank,
        tabRank: analysisStore.tabRank,
        userFlavor: analysisStore.userFlavor
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消分析'
      })
    })
  }
})
</script>

<style scoped>
.ai-analyse-container {
  padding: 20px;
  min-height: calc(100vh - 40px);
  background-color: #f5f7fa;
}

.analysis-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-title {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.loading-container {
  padding: 40px 20px;
}

.loading-text {
  text-align: center;
  color: #909399;
  margin-top: 20px;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.section-title .el-icon {
  margin-right: 8px;
  font-size: 20px;
  color: #409eff;
}

.analysis-result {
  margin-bottom: 30px;
}

.result-content {
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  line-height: 1.8;
  color: #303133;
  white-space: pre-wrap;
}

.chat-section {
  margin-top: 30px;
}

.chat-history {
  height: 400px;
  overflow-y: auto;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
}

.user-message-container {
  flex-direction: row-reverse;
}

.message-avatar {
  margin: 0 12px;
}

.message-bubble {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 8px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

.user-message {
  background-color: #409eff;
  color: white;
}

.ai-message {
  background-color: #ffffff;
  color: #303133;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.input-area {
  position: relative;
  margin-bottom: 40px;
}

.button-group {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 12px;
}

.input-tip {
  position: absolute;
  right: 0;
  bottom: -30px;
  font-size: 12px;
  color: #909399;
  padding: 4px 0;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  resize: none !important;
}

:deep(.el-button) {
  border-radius: 6px;
}

/* 自定义滚动条样式 */
.chat-history::-webkit-scrollbar {
  width: 6px;
}

.chat-history::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 3px;
}

.chat-history::-webkit-scrollbar-track {
  background-color: #f8f9fa;
}
</style>